package com.qidian.server;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.Date;

import com.qidian.common.ClientStatus;
import com.qidian.common.Constants;
import com.qidian.common.Globals;
import com.qidian.common.MessageStatus;
import com.qidian.common.beans.AccountBean;
import com.qidian.common.beans.ClientBean;
import com.qidian.common.beans.GameTypeBean;
import com.qidian.common.beans.MessageBean;
import com.qidian.common.beans.RechargeCardBean;
import com.qidian.common.beans.UserBean;


/**
 * 	MServer，服务类，唯一实例，提供对外接口：
 * 		前缀为'p2s_'的接口处理插件发送至服务器的消息
 * 		前缀为'c2s_'的接口处理答题客户端发送至服务器的消息
 * 		前缀为's_'的接口处理内部的消息
 * 
 **/
public final class MServer
{
   
	private static MServer instance = new MServer() ;
//	private Writer logger ;
	
	private MServer()
	{
//		File file = new File("mserver.log") ;
//		
//		
//		try 
//		{
//			if (!file.exists())
//				file.createNewFile() ;
//			logger = new FileWriter(file);
//			System.out.println(file.getAbsolutePath()) ;
//			logger.write("Start up at " + new java.sql.Timestamp(System.currentTimeMillis())+"\n") ;
//			
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}
	
	public static MServer getInstance()
	{
		if(instance == null)
			instance = new MServer() ;
		return instance ;
	}
	
	/**
	 * 报告错题
	 * 将消息至为错题状态，但并不返回题分，题分将由同步线程在5分钟后返还。
	 * 
	 * */
    public Status p2s_report(long id, String account, String pStatus)
    {
        
        MessageBean mBean = Globals.getMessageBuffer().get(id) ;
        if (mBean == null)
            return Status.INVALID_VALUE ;
        
        // 如果处于错题，或者超时状态
        if (mBean.isReported())
        	return Status.OK ;
        
        // 如果不是本子账号报错
        AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
        if (accountBean == null)
        	return Status.INVALID_VALUE ;
        if (accountBean.getAccountId() != mBean.getAccountId())
        	return Status.INVALID_VALUE ;

        if (pStatus.equalsIgnoreCase("0"))
            mBean.setStatus(MessageStatus.WRONG.status) ;
        else if (pStatus.equalsIgnoreCase("1"))
            mBean.setStatus(MessageStatus.TIME_OUT.status) ;
        else
            return Status.INVALID_VALUE ;
        
        
        /* 此处不返回题分，防止反复报错攻击，在刷入数据库返回题分*/
        
        
        return Status.OK;
    }

    /**
     * 获取答案
     * 
     * */
    public Status p2s_getAnswer(long id, String pUserName, String pMaskCode, StringBuffer result)
    {
        MessageBean mBean = Globals.getMessageBuffer().get(id) ;
        if (mBean == null)
        	return Status.INVALID_VALUE ;
        
        String answer = mBean.getAnswer() ;
        if (answer == null)
        {
        	if (mBean.isTimeOut())
        		return Status.TIME_OUT_MSG ;
        	else
        		return Status.NOT_READY ;
        }
        else
        {
        	if (answer.length() > 0 && answer.charAt(0) == '-')
        		result.append("#"+answer.substring(1)) ;
        	else if (answer.length() == 0 || ">".equalsIgnoreCase(answer))
        		return Status.UNKNOWN_FILE ;
        	else if ("<".equalsIgnoreCase(answer))
        		return Status.DUPLICATE_FILE ;
        	else
        		result.append(answer) ;
        }
        return Status.OK;
    }

    /**
     * 发送文件
     * 
     * @param contentType 文件类型，一般为jpg、gif、bmp、png
     * @param content 文件内容，大小不超过64K
     * @param username 开发者用户名，如果为空表示不绑定开发者
     * @param account 子账号
     * @param gameType 项目类型
     * @param interval 超时时间
     * @param fromIP 发送IP
     * @param fromPort 发送端口
     * @param upoint 开发者自定义扣除点数，如果小于平台的自定义点数，则扣除平台自定义点数
     * @param returnUser 返点开发者用户，如果不指定，默认返回给子账号的主账号
     * 
     * */
    public Status p2s_sendFile(String contentType, byte[] content,
    		String userName,String account, int gameType, 
    		int interval,String fromIP, int fromPort,
    		int uPoint, String returnUser,StringBuffer result)
    {
    	int point ;
    	
		// 检查子账号
        AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
        if (accountBean == null || accountBean.isDeleted())
        	return Status.INVALID_VALUE;
        if (accountBean.isTimeout())
        	return Status.TIME_OUT ;
        if (accountBean.isFreeze())
        	return Status.FREEZE ;
        
        
        // 第一次使用
        if (!accountBean.isUsed())
        	accountBean.setUsed() ;
        
        UserBean mainUser = Globals.getUserBuffer().getById(accountBean.getUserId()) ;
        if (mainUser.isFreeze())
        	return Status.FREEZE ;
        
        //是否绑定开发者
        if(userName != null)
        {
        	UserBean user1 = Globals.getUserBuffer().getByUserName(userName) ;
        	if (user1 == null || user1 != mainUser)
        		return Status.USER_ID_MISMATCH ;
        }
        
        // 检查项目类型、超时时间
        GameTypeBean gameTypeBean = null ;
    	gameTypeBean = Globals.getGameTypeBuffer().get(gameType) ;
    	if (gameTypeBean == null || gameTypeBean.isDeleted())
    		return Status.INVALID_VALUE ;
		point = gameTypeBean.getPoint() ;
		
		// 自定义扣点小于等于0或者大于10000，设置为平台点数
		if (uPoint <= 0 || uPoint > 10000)
			uPoint = point ;
		
		// 超时时间最小为10秒，最大为200秒
		if (interval != 0 && (interval <= Constants.min_interval || interval >= Constants.max_interval))
			return Status.INVALID_VALUE ;

		// 检查子账号点数
		if (accountBean.getLeftPoint()< uPoint)
			return Status.NEED_MORE_POINT ;
		
        // 检查主账号点数
        if (mainUser.getLeftPoint() < uPoint)
        	return Status.NEED_MORE_POINT_MAIN ;
        
        // 返点账号,默认为主账号
        UserBean returnUserBean = mainUser ;
        if (returnUser != null && returnUser.length() > 0)
        {
        	returnUserBean = Globals.getUserBuffer().getByUserName(returnUser) ;
        	if (returnUserBean == null)
        		returnUserBean = mainUser ;
        }
        
        // 自定义点数不能太小，返点数小于(平台扣点-自定义扣点)
        if(returnUserBean.getReturnRatio()*uPoint < (point- uPoint))
        	return Status.INVALID_VALUE ;
		
        // 生成消息
		long msgId = Globals.getIDGenerator().getNextId() ;
        MessageBean message = new MessageBean() ;
        message.setReceiveTime(System.currentTimeMillis()) ;
        message.setId(msgId) ;
        message.setAccountId(accountBean.getAccountId()) ;
        message.setGameType(gameType) ;
        // 如果是自定义超时时间
        if(gameTypeBean.isUdInterval())
        	message.setInterval(interval) ;
        else
        	message.setInterval(gameTypeBean.getMinInterval());
        message.setIp(fromIP) ;
        message.setPort(fromPort) ;
        message.setStatus(MessageStatus.WAIT_TO_ANSWER.status) ;
        message.setContent(content) ;
        message.setContentType(contentType) ;
        message.setUserId(mainUser.getUserId());
        message.setReturnUserId(returnUserBean.getUserId()) ;
        message.setUPoint(uPoint) ;

        // 缓存消息
        if(!Globals.getMessageBuffer().add(message,gameTypeBean))
        	return  Status.SERVER_TOO_BUSY ;

        // 分配消息,增加主账号和子账号已用点数
        accountBean.setLastTime(System.currentTimeMillis()) ;
        accountBean.increaseUsedPoint(uPoint,true) ;
        mainUser.increaseUsedPoint(uPoint) ;
        
        // 返点,5分钟后返回
        returnUserBean.increaseReturnPoint(point,uPoint) ;
        
        result.append(msgId) ;
        return Status.OK ;
    }
    
//    /**
//     * 生成子账号
//     * 1.主账号扣费
//     * 2.生成子账号
//     * 
//     * */
////    private Status p2s_generateAccount(String userName, String password,
////    		int point,long validTime,  StringBuffer result)
////    {
////
////    	if (point < Constants.min_points)
////    		return Status.INVALID_VALUE ;
////    	
////    	UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
////    	if (user == null || !user.getPassword().equals(password))
////    		return Status.INVALID_USERNAME_OR_PASSWORD ;
////    	
////    	if (user.getLeftPoint()< point)
////    		return Status.NEED_MORE_POINT ;
////
////    	AccountBean account = Globals.newAccountBean(user, point, validTime) ; 
////    	if (account == null)
////    		return Status.OTHER_ERROR ;
////    	
////    	result.append(account.getMaskCode()) ;
////    	return Status.OK ;
////    }
    
    /**
     * 批量生成子账号
     * 1.主账号扣费
     * 2.生成子账号
     * 如果余额不足，返回最多能生成的子账号个数
     * */
    public Status p2s_batchGenerateAccount(String userName, String password, 
    		long validTime, int batchSize,int point, StringBuffer result)
    {
    	if (point < Constants.min_points || point > Constants.max_points || 
    			batchSize <= 0 || batchSize > Constants.max_batch_size)
    		return Status.INVALID_VALUE ;
    	
    	UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
    	if (user == null || !user.getPassword().equals(password))
    		return Status.INVALID_USERNAME_OR_PASSWORD ;
    	
    	if (user.isFreeze())
    		return Status.FREEZE ;
    	
    	// 余额不足一个子账号的点数
//    	if (user.getLeftPoint() < point)
//    		return Status.NEED_MORE_POINT ;
    	
    	if (user.isYa())
    		return Status.CALL_TOO_MANY ;
    	
    	AccountBean account = null ;
    	int realCount = 0 ;
    	for(int i = 0 ; i < batchSize ; i++)
    	{
    		account = Globals.newAccountBean(user, point,validTime) ; 
    		if (account != null)
    		{
    			result.append(realCount==0?"":",").append(account.getAccount()) ;
    			realCount++ ;
    		}
    	}

    	return Status.OK ;
    }    
    /**
     * 封停子帐号,必须是创建子账号的用户
     * 1.回收点数
     * 2.删除子帐号
     * @throws IOException 
     * 
     * */
    public Status p2s_recycleAccount(String userName, String password, String account) throws IOException
    {
    	if (userName == null || password == null || account == null)
    		return Status.INVALID_ARGUMENT ;
    	UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
    	if (user == null)
    		return Status.INVALID_VALUE ;
    	if (!user.getPassword().equals(password))
    		return Status.INVALID_USERNAME_OR_PASSWORD ;
    	
    	AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
    	if (accountBean == null)
    		return Status.INVALID_VALUE ;
    	
    	if (accountBean.getUserId() != user.getUserId())
    	{
    		return Status.USER_ID_MISMATCH ;
    	}
    	
    	if (accountBean.isDeleted())
    		return Status.OK ;
    	
//    	user.decreaseUsedPoint(accountBean.getLeftPoint()) ;
    	accountBean.setDeleted() ;
    	
    	return Status.OK ;
    }

//    /**
//     * 生成充值卡号
//     * 
//     * 
//     * */
//    private Status p2s_generateRenewCode(String userName, String password,
//    		long validTime, int point, StringBuffer result)
//    {
//    	if (userName == null || password == null)
//    		return Status.INVALID_ARGUMENT ;
//    	if (point < Constants.min_points)
//    		return Status.INVALID_VALUE ;
//    	
//    	UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
//    	if (user == null)
//    		return Status.INVALID_VALUE ;
// 
//    	if (!user.getPassword().equals(password))
//    		return Status.INVALID_USERNAME_OR_PASSWORD ;
// 
//       	if (user.getLeftPoint() < point)
//    		return Status.NEED_MORE_POINT ;
//    	
//    	RechargeCardBean rechargeCard = Globals.newRechargeCard(user,point,validTime) ;
//    	
//    	result.append(rechargeCard.getRechargeCode()) ;
//    	return Status.OK ;
//    }
    /**
     * 批量生成充值卡
     * 
     * 
     * */
    public Status p2s_batchGenerateRenewCard(String userName, String password, 
    		long validTime,int batchSize, int point, StringBuffer result)
    {
    	if (userName == null || password == null)
    		return Status.INVALID_ARGUMENT ;
    	if (point < Constants.min_points || point > Constants.max_points)
    		return Status.INVALID_VALUE ;
    	
    	UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
    	if (user == null)
    		return Status.INVALID_VALUE ;
 
    	if (!user.getPassword().equals(password))
    		return Status.INVALID_USERNAME_OR_PASSWORD ;
 
    	// 余额不足一张充值卡的点数
       	if (user.getLeftPoint() < point)
    		return Status.NEED_MORE_POINT_MAIN ;
       	
    	if (user.isYr())
    		return Status.CALL_TOO_MANY ;
    	
    	
       	int realCount = 0 ;
    	for(int i = 0 ; i < batchSize;  i ++)
    	{
    		RechargeCardBean rechargeCard = Globals.newRechargeCard(user,point,validTime) ;
    		if (rechargeCard != null)
    		{
    			result.append(realCount==0?"":",").append(rechargeCard.getRechargeCode()) ;
    			realCount ++ ;
    		} 
    		else if (result.length() == 0)
    		{
    			return Status.OTHER_ERROR ;
    		}
    	}
    	return Status.OK ;
    }    
    /**
     * 账号续费
     * 1.新账号减少点数
     * 2.旧账号减少点数
     * 
     * */
    public Status p2s_rechargeAccount(String account, String rechargeCard, StringBuffer result)
    {
    	if (account == null || rechargeCard == null)
    		return Status.INVALID_ARGUMENT ;
    	
    	AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
    	if (accountBean == null)
    		return Status.INVALID_CODE ;
    	if (accountBean.isTimeout())
    		return Status.TIME_OUT ;
    	if (accountBean.isDeleted())
    		return Status.INVALID_CODE ;
    	
    	RechargeCardBean rechargeCardBean = Globals.getRechargeCardBuffer().get(rechargeCard) ;
    	if (rechargeCardBean == null)
    		return Status.INVALID_CODE ;
    	if (rechargeCardBean.isTimeout())
    		return Status.TIME_OUT ;
    	if (rechargeCardBean.isUsed())
    		return Status.USED_RECHARGE_CARD ;
    	
    	if (rechargeCardBean.getUserId() != accountBean.getUserId())
    		return Status.USER_ID_MISMATCH ;
    	int prePoint = accountBean.getLeftPoint() ;
    	int point = rechargeCardBean.getPoint() ;
    	
    	accountBean.recharge(rechargeCardBean) ;
    	result.append(rechargeCardBean.getPoint()) ;
    	
    	Globals.logger(System.currentTimeMillis(), 
    			"rechargeAccount", account, rechargeCard,
    			prePoint+","+point, String.valueOf(accountBean.getUserId())) ;    	
    	
    	return Status.OK ;
    }
    
    /**
     * 查询子账号信息,该操作会激活账号
     * 
     * */
    public Status p2s_queryAccount(String username, String account, StringBuffer result)
    {
    	
    	AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
    	if (accountBean == null || accountBean.isDeleted())
    		return Status.INVALID_VALUE ;
    	
    	UserBean userBean = null ;
    	if (username != null)
    	{
    		userBean = Globals.getUserBuffer().getByUserName(username) ;
    		if (userBean == null)
    			return Status.INVALID_VALUE ;
    		if (userBean.getUserId() != accountBean.getUserId())
    			return Status.USER_ID_MISMATCH ;
    	}
    	
    	// 如果带主账号,则子激活账号 
    	if (userBean != null && !accountBean.isUsed())
    		accountBean.setUsed() ;

		result.append(accountBean.getPoint()).append(",")
		.append(accountBean.getUsedPoint()).append(",") 
		.append(accountBean.getLeftPoint()).append(",") ;
//		Date date = new Date(accountBean.getValidTime());
		java.sql.Timestamp time = new java.sql.Timestamp(accountBean.getValidTime()) ;
		String strTime = String.format("%4d-%02d-%02d %02d:%02d:%02d", 1900+time.getYear()
				,time.getMonth()+1,time.getDate(),time.getHours(),time.getMinutes(),time.getSeconds()) ;
		
		result.append(strTime) ;
    	
    	return Status.OK ;
    }
    
    public Status p2s_queryAllAccount(String userName,String password, StringBuffer result,
    		int start , int end)
    {
    	return Status.OK ;
    }
    
    /**
     * 查询用户点数信息
     * 返回格式:可用点数,返点数量
     * 
     * */    
    public Status p2s_queryUser(String userName, String password, StringBuffer result)
    {
    	UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
    	if (user == null)
    		return Status.INVALID_VALUE ;
    	if (!user.getPassword().equals(password))
    		return Status.INVALID_USERNAME_OR_PASSWORD ;
    	result.append(user.getLeftPoint()).append(",").append((long)user.getReturnPoint()) ;
    	return Status.OK ;
    }
    
    /**
     * 根据用户名获取用户对象
     * 
     * */
	public UserBean p2s_getUser(String userName) 
	{
		if (userName == null)
			return null ;
		return Globals.getUserBuffer().getByUserName(userName) ;
	}

    /**
     * 发送答案
     * 
     * */
	public Status c2s_sendAnswer(String strMsgId, String answer, long clientId, String password) throws IOException
	{				
		if (answer == null || strMsgId == null || password == null)
			return Status.INVALID_ARGUMENT ;

		answer = java.net.URLDecoder.decode(answer,"UTF-8") ;

		double point = 0 ;
		int updatedCount = 0;
		
		Long msgId = Long.parseLong(strMsgId) ;
		MessageBean msg = Globals.getMessageBuffer().get(msgId) ;
		ClientBean client = Globals.getClientBuffer().getClient(msg.getClientId()) ;
		if (msg != null)
		{
			if (msg.getClientId() - clientId != 0)
				return Status.INVALID_VALUE ;
			if (!client.getPassword().equalsIgnoreCase(password))
				return Status.INVALID_USERNAME_OR_PASSWORD ;
			
			// 已经回答
			if (msg.getAnswer() != null)
				return Status.OK ;
			
		    msg.setAnswer(answer) ;
		    msg.setAnswerTime(System.currentTimeMillis()) ;
		    msg.setStatus(MessageStatus.ANSWERED.status);
			
		    GameTypeBean gameType = Globals.getGameTypeBuffer().get(msg.getGameType()) ;
			point += gameType.getPoint_worker() ;
			updatedCount ++;
		}
		else
			return Status.INVALID_VALUE ;
		
		// 更新客户端信息，增加点数
	    
	    if (client == null)
	        return Status.INVALID_VALUE ;
	    client.addAnswerCount(updatedCount, point) ;
	    client.setLastActiveTime(System.currentTimeMillis()) ;
		
		return Status.OK ;
	}
	
    
    /**
     * 发送多个答案
     * 
     * */
	public Status c2s_sendAnswers(String answers, long clientId, String password) throws IOException
	{				
		answers = java.net.URLDecoder.decode(answers,"UTF-8") ;
		String[] splits = answers.split("#") ;
		if (splits[0].length() == 0)
			return Status.INVALID_VALUE ;
		
		String msgId ;
		String answer ;
		int updatedCount = 0 ;
		double point = 0 ;
		MessageBean msg = null ;
//		Long clientId = -1L ;
	    ClientBean client = null ;
		for (int i = 0 ; i < splits.length ; i++)
		{
			String [] contents = splits[i].split(":") ;
			msgId = contents[0] ;
			if (contents.length == 1)
				answer = "" ;
			else
			{
				answer = contents[1] ;
			}
			Long id = Long.parseLong(msgId) ;
			msg = Globals.getMessageBuffer().get(id) ;
			if (msg == null || msg.getClientId() != clientId)
//				return Status.INVALID_VALUE ;
				continue ;

			// 客户端ID不匹配或密码不正确
			client = Globals.getClientBuffer().getClient(msg.getClientId()) ;
			if (client == null)
				continue ;
			if ( (msg.getClientId()!= clientId ) ||
					!client.getPassword().equalsIgnoreCase(password))
				continue ;
			
			// 已回答
			if (msg.getAnswer() != null)
				continue ;
			
			
		    msg.setAnswer(answer) ;
		    msg.setAnswerTime(System.currentTimeMillis()) ;
		    msg.setStatus(MessageStatus.ANSWERED.status);
			
			GameTypeBean gameType = Globals.getGameTypeBuffer().get(msg.getGameType()) ;
			point += gameType.getPoint_worker() ;
			updatedCount ++;
//			if(clientId < 0)
//				clientId = msg.getClientId() ;

		}
//		if(clientId < 0)
//			return Status.OTHER_ERROR ;
		
		// 更新客户端信息
	    if (client != null)
	    {
		    client.addAnswerCount(updatedCount, point) ;
		    client.setLastActiveTime(System.currentTimeMillis()) ;
	    }
		
		return Status.OK ;
	}
	
	/**
	 * 客户端提交误报
	 * 
	 * */
	public Status c2s_reportWrongAnswers(String msgIds)
	{
		return Status.OK ;
	}
	
	
	/**
	 * 提交误报
	 * 
	 * */
	public Status reportWrongAnswer(String msgId)
	{
		return Status.OK ;
	}
	
	/**
	 *  获取计数信息
	 * 
	 * */
	public Status c2s_getCount(String strClientId ,StringBuffer result)
	{
	    if (strClientId == null)
	        return Status.INVALID_ARGUMENT ;
	    
	    ClientBean client = Globals.getClientBuffer().getClient(strClientId) ;
	    if (client == null)
	        return Status.INVALID_ARGUMENT ;
//	    if (!client.isActive())
//	        return Status.NO_ACTIVE_CLIENT ;
	    client.setLastActiveTime(System.currentTimeMillis()) ;
	    result.append("[{\"answerCount\":").append(client.getAnswered()).append(",\"wrongCount\":") ;
	    result.append(client.getWrong()).append(",\"waitCount\":").append(Globals.getMessageBuffer().getWaitSize());
	    result.append(",\"point\":").append(client.getPoint());
	    result.append("}]");
	    return Status.OK ;
	}
	
	/**
	 * 获取媒体文件内容
	 * 
	 * */
	public byte[] c2s_getFile(String strMsgID, StringBuffer contentType)
    {
		if (strMsgID == null)
			return null ;
		
	    Long msdID = Long.parseLong(strMsgID) ;
	    
	    MessageBean mBean = Globals.getMessageBuffer().get(msdID) ;
	    if(mBean == null)
	    	return null ;
	    contentType.append(mBean.getContentType()) ;
	    return mBean.getContent() ;

    }	
	
	/**
	 * 
	 *  客户端登陆
	 *  
	 * */
	public ClientBean c2s_login(String userName, String password,String key)
	{
		if(!Constants.key.equalsIgnoreCase(key))
			return null ;
		
		return Globals.getClientBuffer().login(userName, password) ;
	}
	
	/**
	 * 客户端是否已登陆
	 * 
	 * */
	public boolean c2s_checkClientLogin(String userName)
	{
		ClientBean client = Globals.getClientBuffer().getClientByName(userName) ;
		if (client != null && client.isActive())
			return true ;
		return false ;
	}
	
	/**
	 * 返还账号点数:
	 * 如果已经回答，账号使用点数减少，客户端点数减少；
	 * 如果未回答，只坚守账号点数。
	 * 用于同步线程检测到非正确题目后的操作
	 * 
	 * */
	public void s_returnAccountPoint(MessageBean msg)
	{
		AccountBean account = Globals.getAccountBuffer().get(msg.getAccountId()) ;
		GameTypeBean gameType = Globals.getGameTypeBuffer().get(msg.getGameType()) ;
		
		if(account == null || gameType == null)
			return ;
		
		int uPoint = msg.getUPoint() ;
		int point = gameType.getPoint() ;
		// 如果已经被回答，则减少子账户和主账号的已用点数、返点账号的返点数，并且客户端需要减少点数;
		if (msg.getAnswerTime() > 0)
		{
			ClientBean client = Globals.getClientBuffer().getClient(msg.getClientId()) ;
			UserBean user = Globals.getUserBuffer().getById(account.getUserId());
			client.addWrongCount(1, gameType.getPoint_worker()) ;
//			int subPoint = uPoint ;
//			int mainPoint = uPoint>=point?uPoint:point;
			account.decreaseUsedPoint(uPoint) ;
			user.decreaseUsedPoint(uPoint) ;
			UserBean returnUser = Globals.getUserBuffer().getById(msg.getReturnUserId()) ;
			returnUser.decreaseReturnPoint(point,uPoint) ;
		}
		else
		{// 否则只减少子账号和主账号的已用点数、返点账号的返点数
			UserBean user = Globals.getUserBuffer().getById(account.getUserId());
			account.decreaseUsedPoint(uPoint) ;
			user.decreaseUsedPoint(uPoint) ;
			UserBean returnUser = Globals.getUserBuffer().getById(msg.getReturnUserId()) ;
			returnUser.decreaseReturnPoint(point,uPoint) ;
		}
	}
    /**
     * 封停子帐号,供超级管理员使用
     * 1.删除子帐号
     * 
     * */
    public Status s_recycleAccount(String account)
    {    	
    	AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
    	if (accountBean == null)
    		return Status.INVALID_VALUE ;
    	    	
    	if (accountBean.isDeleted())
    		return Status.OK ;

    	accountBean.setDeleted() ;
    	
    	return Status.OK ;
    }	
    /**
     * 封停用户,供超级管理员使用
     * 1.删除主账号
     * 2.删除其所有子帐号
     * 
     * */
    public Status s_recycleUser(String username)
    {    	
    	UserBean userBean = Globals.getUserBuffer().getByUserName(username) ;
    	if (userBean == null)
    		return Status.INVALID_VALUE ;

    	if (userBean.isDeleted())
    		return Status.OK ;

    	userBean.setDeleted() ;
    	
    	return Status.OK ;
    }
	
	/**
	 * 
	 *  注销
	 *   
	 * */
	public Status c2s_logout(String clientId,String userName, String password)
	{
		if (clientId == null)
			return Status.INVALID_ARGUMENT ;
		ClientBean client = Globals.getClientBuffer().getClient(clientId) ;
		if (client == null)
			return Status.INVALID_VALUE ;
		if (!client.getClientName().equalsIgnoreCase(userName) || !client.getPassword().equals(password))
			return Status.INVALID_VALUE ;
		client.setStatus(ClientStatus.NoActive) ;
		
		return Status.OK ;
	}	
	
	/**
	 * 生成充值卡号
	 * 
	 * */
	public Status s_generateRenewCode(int point,long validTime,StringBuffer result)
	{
		if (point < Constants.min_points)
			return Status.INVALID_VALUE ;
		UserBean user = Globals.getUserBuffer().getByUserName(Constants.super_user_name) ;
		RechargeCardBean rechargeCard = Globals.newRechargeCard(user,point,validTime) ;
		if (rechargeCard == null)
			return Status.OTHER_ERROR ;
		result.append(rechargeCard.getRechargeCode()) ;
		return Status.OK ;
	}
	
	/**
	 * 注册用户
	 * 
	 * */
	public Status s_regUser(String userName, String password, String qq, String email,
			String zhifubao, String phone, int userType)
	{
		if (userName == null || password == null ||
				qq == null || email == null)
			return Status.INVALID_ARGUMENT ;
		
		if (!UserBean.isValidPassword(password) || !UserBean.isValidUserName(userName))
			return Status.INVALID_VALUE ;
		if( qq.length() >= 12 || email.length() >= 32 ||
				qq.indexOf('\'') >= 0 || qq.indexOf('"') >= 0 ||
				email.indexOf('\'') >= 0 || email.indexOf('"') >= 0)
			return Status.INVALID_VALUE ;
		
		UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
		if (user != null)
			return Status.USER_EXISTS ;
		
		user = Globals.newUserBean(userName, password, 0, qq ,email,
				zhifubao,phone,userType,0.0) ;
		if (user == null)
			return Status.OTHER_ERROR ;
		
		return Status.OK ;
	}
	
	public static void main(String[] args) throws InterruptedException
	{
		MServer mserver = getInstance() ;
		StringBuffer result = new StringBuffer() ;
		mserver.s_generateRenewCode(10000,10000, result) ;
//		System.out.println(result) ;
//		Thread.sleep(10000) ;
		String userName = "user002" ;
		String password = "pwd002" ;
		String qq = "12344" ;
		String email = "111" ;
		for (int i = 0 ; i < 10 ; i ++)
		{
			userName = "user00"+i;
			password = "pwd00"+ i;
			Status status = mserver.s_regUser(userName, password,qq,email,null,null,0) ;
			System.out.println(status.getDescription()) ;
		}
		System.exit(-1) ;
	}

	/**
	 * 用户登录
	 * 
	 * */
	public Status s_login(String userName, String password) 
	{
		if (userName == null || password == null)
			return Status.INVALID_ARGUMENT ;
		UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
		if (user == null || !user.getPassword().equals(password))
			return Status.INVALID_USERNAME_OR_PASSWORD ;
		return Status.OK;
	}

	/**
	 * 用户充值：
	 * 结果返回充值的点数
	 * 只能使用超级用户生成的充值卡
	 * 
	 * */
	public Status p2s_rechargeUser(String userName, String rechargeCode,
			StringBuffer result) 
	{
		if (userName == null || rechargeCode == null)
			return Status.INVALID_ARGUMENT ;
		UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
		if (user == null)
			return Status.INVALID_VALUE ;
		RechargeCardBean rechargeCard = Globals.getRechargeCardBuffer().get(rechargeCode) ;
		if (rechargeCard == null)
			return Status.INVALID_CODE ;
		if (rechargeCard.isTimeout())
			return Status.TIME_OUT ;
		
		// 只有超级用户生成的充值卡才能用于开发者充值
		UserBean superUser = Globals.getUserBuffer().getByUserName(Constants.super_user_name) ;
		if (rechargeCard.getUserId() != superUser.getUserId())
    		return Status.INVALID_VALUE ;
		
		if (rechargeCard.isUsed())
    		return Status.USED_RECHARGE_CARD ;
    	
		int prePoint = user.getLeftPoint() ;
    	int point = rechargeCard.getPoint() ;
    	rechargeCard.setUsed(1) ;
    	user.increasePoint(point);
    	result.append(point);
    	
    	// 如果第一次充值，设置返点率为30%
    	if (user.getPoint() <= 0 && user.getReturnRatio() <= 0.00000001)
    		user.setReturnRatio(Constants.init_return_ratio) ;
    	Globals.logger(System.currentTimeMillis(), 
    			"rechargeUser", user.getUserName(), rechargeCard.getRechargeCode(),
    			prePoint+","+point, String.valueOf(user.getUserId())) ;
		return Status.OK;
	}

	public Status p2s_recycleRechargeCard(String userName, String password,
			String rechargeCard) 
	{
    	if (userName == null || password == null || rechargeCard == null)
    		return Status.INVALID_ARGUMENT ;
    	UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
    	if (user == null)
    		return Status.INVALID_VALUE ;
    	if (!user.getPassword().equals(password))
    		return Status.INVALID_USERNAME_OR_PASSWORD ;
    	

    	RechargeCardBean rechargeCardBean = Globals.getRechargeCardBuffer().get(rechargeCard);
    	if (rechargeCardBean == null || rechargeCardBean.isDeleted())
    		return Status.INVALID_VALUE ;
    	if (rechargeCardBean.isTimeout())
    		return Status.TIME_OUT ;
    	
    	if (rechargeCardBean.getUserId() != user.getUserId())
    		return Status.INVALID_VALUE ;
    	if (rechargeCardBean.isUsed())
    		return Status.OK ;
    
//    	user.decreaseUsedPoint(rechargeCardBean.getPoint());
    	rechargeCardBean.setUsed(1) ;
    	
    	return Status.OK ;
	}

	/**
	 * 客户端申请消息
	 * 
	 * */
	public Status c2s_getMsg(String strClientId, String strMsgCount,String password,String key,
			StringBuffer result) 
	{
		if (strClientId == null || strMsgCount == null || key == null || password == null)
			return Status.INVALID_ARGUMENT ;
		
		if (!Constants.key.equalsIgnoreCase(key))
			return Status.INVALID_VALUE ;
		
		int msgCount = Constants.max_msg_per_request ;
		msgCount = Integer.parseInt(strMsgCount) ;
		
		ClientBean client = Globals.getClientBuffer().getClient(strClientId) ;
        if (client == null)
            return Status.INVALID_ARGUMENT ;
        if (!client.getPassword().equalsIgnoreCase(password))
        	return Status.INVALID_VALUE ;
        
		client.setLastActiveTime(System.currentTimeMillis()) ;
        
        result.append("[{") ;
        result.append("\"msg\":");
		result.append("[") ;
        MessageBean msg = null ;
        GameTypeBean gameType = null ;
        int i = 0 ; 
		while(i < msgCount)
		{
			msg = Globals.getMessageBuffer().poll() ;
			if(msg == null)
				break ;
			client.markMsg(msg) ;
			gameType = Globals.getGameTypeBuffer().get(msg.getGameType()) ;
			if(i > 0)
				result.append(",");
			
			// msgId,contentType,answerLen,answerType,timeOut
			result.append("{\"msgId\":").append(msg.getId())
				.append(",\"contentType\":\"").append(msg.getContentType()).append("\"")
				.append(",\"gameType\":").append(gameType.getGameType())
				.append(",\"answerLen\":").append(gameType.getAnswerLen())
				.append(",\"answerType\":\"").append(gameType.getAnswerTypeDes()).append("\"")
				.append(",\"timeOut\":").append(( msg.getReceiveTime()- System.currentTimeMillis())/1000 + msg.getInterval())
				.append(",\"recvTime\":").append(msg.getReceiveTime())
				.append(",\"interval\":").append(msg.getInterval())
				.append("}");
			i++;
			
		}
		result.append("]");
		result.append(",\"waitCount\":").append(Globals.getMessageBuffer().getWaitSize()) ;
	    result.append(",\"answerCount\":").append(client.getAnsweredToday());
	    result.append(",\"wrongCount\":").append(client.getWrongToday());
	    result.append(",\"point\":").append(String.format("%.03f", client.getPointToday()));
		result.append("}]");
		
//		if (i > 0)
//		{
//			try {
//				logger.write(result.toString()+"\n") ;
//				logger.flush();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
		
        return Status.OK ;		
	}
	/**
	 * 超级客户端申请转发消息
	 * 转发类型、抓发
	 * 
	 * */
	public Status c2s_getTransMsg(String strClientId,
			String password,
			String strMsgCount,String strTransType,
			StringBuffer result) 
	{
		if (strClientId == null || strMsgCount == null || strTransType == null ||
				password == null)
			return Status.INVALID_ARGUMENT ;
		
		int transType = 0 ;
		if (strTransType != null && strTransType.length() > 0)
			transType = Integer.parseInt(strTransType) ;
		int msgCount = Constants.max_msg_per_request ;
		msgCount = Integer.parseInt(strMsgCount) ;
		
		ClientBean client = Globals.getClientBuffer().getClient(strClientId) ;
        if (client == null)
            return Status.INVALID_ARGUMENT ;
        if (!client.getPassword().equalsIgnoreCase(password))
        	return Status.INVALID_VALUE ;
		client.setLastActiveTime(System.currentTimeMillis()) ;
        
        result.append("[{") ;
        result.append("\"msg\":");
		result.append("[") ;
        MessageBean msg = null ;
        GameTypeBean gameType = null ;
        int i = 0 ; 
		while(i < msgCount)
		{
			
			msg = Globals.getMessageBuffer().pollTrans(transType) ;
			if(msg == null)
				break ;
			client.markMsg(msg) ;
			gameType = Globals.getGameTypeBuffer().get(msg.getGameType()) ;
			if(i > 0)
				result.append(",");
			// msgId,contentType,answerLen,answerType,timeOut
			result.append("{\"msgId\":").append(msg.getId())
				.append(",\"contentType\":\"").append(msg.getContentType()).append("\"")
				.append(",\"gameType\":").append(gameType.getGameType())
				.append(",\"answerLen\":").append(gameType.getAnswerLen())
				.append(",\"answerType\":\"").append(gameType.getAnswerType()).append("\"")
				.append(",\"timeOut\":").append(( msg.getReceiveTime()- System.currentTimeMillis())/1000 + msg.getInterval())
				.append(",\"recvTime\":").append(msg.getReceiveTime())
				.append(",\"interval\":").append(msg.getInterval())
				.append("}");
			i++;
		}
		result.append("]");
		result.append(",\"waitCount\":").append(Globals.getMessageBuffer().getWaitSize()) ;
	    result.append(",\"answerCount\":").append(client.getAnswered());
	    result.append(",\"wrongCount\":").append(client.getWrong());
	    result.append(",\"point\":").append(client.getPoint());
		result.append("}]");
        
        return Status.OK ;		
	}	

	public Status s_createGameType(String gameDescription, int answerType,
			int answerLen, int min_interval ,int point, double pointWorker,int transOn,
			double difficulty, StringBuffer result) 
	{
		GameTypeBean gameType = Globals.newGameTypeBean(gameDescription, answerType, answerLen, 0, point, pointWorker, min_interval,transOn,difficulty) ;
		if (gameType != null)
		{
			result.append(gameType.getGameType()) ;
			return Status.OK ;
		}
		return Status.OTHER_ERROR;
	}

	public Status s_deleteGameType(int gameType) 
	{
		Globals.removeGameType(gameType) ;
		return Status.OK;
	}
	public Status s_updateGameType(int gameType,String gameDesc, int point,
			double pointWorker,int answerType,int answerLen,int interval, int transOn,
			double difficulty)
	{
		GameTypeBean gameTypeBean = Globals.updateGameType(gameType, gameDesc, point, pointWorker, answerType, answerLen, interval, transOn,difficulty) ;
		if (gameTypeBean == null)
			return Status.OTHER_ERROR ;
		return Status.OK ;
	}

	public Status s_updateUser(String userName, String password,
			String newPassword, String qq, String email,String zhifubao, String phone) 
	{
		if (!UserBean.isValidPassword(password) || !UserBean.isValidPassword(newPassword)||
				!UserBean.isValidEmail(email) || !UserBean.isValidQQ(qq) ||
				!UserBean.isValidPhone(phone) || !UserBean.isValidZhifubao(zhifubao))
			return Status.INVALID_ARGUMENT ;
		
		UserBean userBean = Globals.updateUser(userName,password,newPassword,qq,email,
				zhifubao,phone) ;
		if (userBean == null)
			return Status.OTHER_ERROR;
		return Status.OK;
	}

	/**
	 * 通过用户名、充值卡创建账号
	 * 
	 * */
	public Status p2s_createAccountByRechargeCard(String userName,
			String rechargeCard, StringBuffer result) 
	{
		UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
		RechargeCardBean rcBean = Globals.getRechargeCardBuffer().get(rechargeCard) ;
		if (user == null || rcBean == null)
			return Status.INVALID_VALUE ;
		// 必须是开发者自己创建的有效充值卡
		if(rcBean.isUsed() || rcBean.isDeleted() ||
				rcBean.getUserId() != user.getUserId())
			return Status.INVALID_VALUE ;
		long validTime = System.currentTimeMillis() + 5L*Constants.millseconds_per_year ;
		Status status = p2s_batchGenerateAccount(userName, user.getPassword(), validTime, 1, rcBean.getPoint(), result);
		if (status == Status.OK)
			rcBean.setUsed(1) ;
		return status;
	}
	/**
	 * 合并子账号，将子账号B的点数合并到子账号A
	 * 
	 * 
	 * */
	public Status p2s_mergeAccount(String accountA, String accountB,
			StringBuffer result) 
	{
		if (accountA == null || accountB == null)
			return Status.INVALID_ARGUMENT ;
		
		// 同一帐号不可合并
		if (accountA.equalsIgnoreCase(accountB))
			return Status.INVALID_VALUE ;
		
		// 无效帐号不可合并
		AccountBean aBean = Globals.getAccountBuffer().get(accountA) ;
		AccountBean bBean = Globals.getAccountBuffer().get(accountB) ;
		if (!AccountBean.isValid(aBean) || !AccountBean.isValid(bBean))
			return Status.INVALID_VALUE ;
		
		// 冻结账号不可合并
		if (aBean.isFreeze() || bBean.isFreeze())
			return Status.FREEZE ;
		
		// 非同源帐号不可合并
		if (aBean.getUserId() != bBean.getUserId())
			return Status.USER_ID_MISMATCH ;
		
		int leftPoint = 0 ;// 账号B点数
		int prePoint = 0 ;// 账号A点数
		synchronized(this){
			if (bBean.isDeleted() || aBean.isDeleted())
				return Status.INVALID_VALUE;
			leftPoint = bBean.getLeftPoint() ;
			prePoint = aBean.getLeftPoint() ;
			aBean.increasePoint(leftPoint) ;
			bBean.increaseUsedPoint(leftPoint,false) ;
			// 设置为已使用
			aBean.setUsed() ;
			bBean.setUsed() ;
			long validTime = bBean.getValidTime() ;
	    	if(validTime > aBean.getValidTime())
	    		aBean.setValidTime(validTime) ;
	    	
	    	// 设置B账号为删除
	    	bBean.setDeleted() ;
		}
		
		result.append(aBean.getPoint()).append(",")
		.append(aBean.getUsedPoint()).append(",") 
		.append(aBean.getLeftPoint()).append(",") ;
		Date date = new Date(aBean.getValidTime());
		result.append(date) ;
		Globals.logger(System.currentTimeMillis(),
				"mergeAccount", aBean.getAccount(), bBean.getAccount(), 
				prePoint+","+leftPoint, String.valueOf(aBean.getUserId())) ;
		return Status.OK;
	}

	/**
	 * 新建客户端,返回状态
	 * 如果成功，result包含客户端ID
	 * 
	 * */
	public Status s_createClient(String clientName, String password,String name, String phone, StringBuffer result) 
	{
		ClientBean client = Globals.newClientBean(clientName, password,  name,  phone) ;
		
		if (client != null)
		{
			result.append(client.getClientId()) ;
			return Status.OK ;
		}
		return Status.OTHER_ERROR;
	}

	public Status s_updateClient(long clientId, String password,
			String name, String phone) 
	{
		ClientBean clientBean = Globals.updateClient(clientId, password,name, phone) ;
		if (clientBean == null)
			return Status.OTHER_ERROR ;
		return Status.OK ;
	}

	public Status s_deleteClient(long clientId) {

//		Globals.removeClient(clientId) ;
		ClientBean client = Globals.getClientBuffer().getClient(clientId) ;
		if (client != null)
			client.setDeleted() ;
		return Status.OK;
	}

	public Status s_deleteUser(long userId) {
//		Globals.removeUser(userId) ;
		UserBean user = Globals.getUserBuffer().getById(userId) ;
		if (user != null)
			user.setDeleted() ;
		return Status.OK ;
	}

	/**
	 * 插入子账号
	 * 
	 * */
	public Status p2s_createAccountA(String userName, String password,
			long validTime, String account, int point, StringBuffer result) 
	{
		if (point < Constants.min_points || point > Constants.max_points )
    		return Status.INVALID_VALUE ;
    	
    	UserBean user = Globals.getUserBuffer().getByUserName(userName) ;
    	if (user == null || !user.getPassword().equals(password))
    		return Status.INVALID_USERNAME_OR_PASSWORD ;
    	
    	if (user.isFreeze())
    		return Status.FREEZE ;
    	
    	// 余额不足一个子账号的点数
//    	if (user.getLeftPoint() < point)
//    		return Status.NEED_MORE_POINT ;
    	if (user.isYa())
    		return Status.CALL_TOO_MANY ;
		
		String maskCode = user.getUserId()+"S"+account ;
		if (!AccountBean.isValidFormat(maskCode))
			return Status.INVALID_VALUE ;
		if (Globals.getAccountBuffer().get(maskCode) != null)
			return Status.USER_EXISTS ;
		
		AccountBean accountBean = Globals.newAccountBean(user, point, maskCode, validTime) ;
		if (accountBean != null)
			result.append(accountBean.getAccount()) ;
		else
			return Status.OTHER_ERROR ;
		
		return Status.OK;
	}
	
	/**
	 * 预检查
	 * 
	 * 
	 * */
	public Status p2s_preSendFile(String userName, String account, String gameType)
	{
		// 检查子账号
        AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
        if (accountBean == null || accountBean.isDeleted())
        	return Status.INVALID_VALUE;
        if (accountBean.isFreeze())
        	return Status.FREEZE ;
        if (accountBean.isTimeout())
        	return Status.TIME_OUT ;
        if (accountBean.getLeftPoint() < 10)
        	return Status.NEED_MORE_POINT ;
		return Status.OK ;
	}

	/**
	 * 更新开发者返点率
	 * 
	 * 
	 * */
	public Status s_updateUser(long userId, double returnRatio) 
	{
		UserBean user = Globals.getUserBuffer().getById(userId) ;
		if (user == null)
			return Status.INVALID_VALUE ;
		if (returnRatio >= 1.0f || returnRatio < 0.0f)
			return Status.INVALID_VALUE ;
		user.setReturnRatio(returnRatio) ;
		return Status.OK ;
	}
	
	/**
	 * 返点转换为可用点数
	 * 返回转换的实际点数
	 * 
	 * */
	public Status s_returnPoint2Point(long userId, int point,StringBuffer result)
	{
		UserBean user = Globals.getUserBuffer().getById(userId) ;
		int maxReturnPoint = (int) user.getReturnPoint() ;
		if (point <= 0 || point > maxReturnPoint)
			point =  maxReturnPoint;
//		user.decreaseUsedPoint(point) ;
		user.increasePoint(point) ;
		user.decreaseReturnPoint(point) ;
		result.append(point) ;
		return Status.OK ;
	}

	public Status s_unfreezeAccount(UserBean user, String account) 
	{
		if (account == null || user == null)
			return Status.INVALID_ARGUMENT ;
		
		AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
		if (accountBean == null)
			return Status.INVALID_VALUE ;
		if ( !user.isSupperUser() && user.getUserId() != accountBean.getUserId())
			return Status.USER_ID_MISMATCH ;
		accountBean.unfreeze() ;
		return Status.OK;
	}

	public Status s_freezeAccount(UserBean user,String account) {
		if (account == null || user == null)
			return Status.INVALID_ARGUMENT ;
		
		AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
		if (accountBean == null)
			return Status.INVALID_VALUE ;
		if ( !user.isSupperUser() && user.getUserId() != accountBean.getUserId())
			return Status.USER_ID_MISMATCH ;
		accountBean.freeze() ;
		return Status.OK;
	}

	public Status s_unfreezeUser(String username) {
		if (username == null)
			return Status.INVALID_ARGUMENT ;
		
		UserBean userBean = Globals.getUserBuffer().getByUserName(username) ;
		if (userBean == null)
			return Status.INVALID_VALUE ;
		userBean.unfreeze() ;
		return Status.OK;
	}

	public Status s_freezeUser(String username) {
		if (username == null)
			return Status.INVALID_ARGUMENT ;
		
		UserBean userBean = Globals.getUserBuffer().getByUserName(username) ;
		if (userBean == null)
			return Status.INVALID_VALUE ;
		userBean.freeze() ;
		return Status.OK;
	}

	/**
	 * 误报处理，工人增加2倍点数，主账号、子账号扣除2倍点数(无返点)
	 * 
	 * */
	public Status c2s_reportWrongAnswer(String msgId) 
	{
		MessageBean msg = Globals.getMsg(msgId) ;
		
		if (msg == null)
			return Status.OK ;
		
		if (msg.getStatus() != MessageStatus.WRONG.status)
			return Status.OK ;
		
		UserBean user = Globals.getUserBuffer().getById(msg.getUserId()) ;
		AccountBean account = Globals.getAccountBuffer().get(msg.getAccountId()) ;
		ClientBean client = Globals.getClientBuffer().getClient(msg.getClientId()) ;
		GameTypeBean gameType = Globals.getGameTypeBuffer().get(msg.getGameType()) ;
		
		int point = gameType.getPoint() ;
		double point_worker = gameType.getPoint_worker() ;
		
		if (user != null)
			user.increaseUsedPoint((int)(msg.getUPoint()*Constants.ratio_report_wrong)) ;
		if (account != null)
			account.increaseUsedPoint((int)(point*Constants.ratio_report_wrong), false) ;
		if (client != null)
		{
//			client.addAnswerCount(0, point_worker*Constants.ratio_report_wrong) ;
			client.addWrongCount(-1, -point_worker*Constants.ratio_report_wrong);
		}
		
		if(!Globals.updateMsg(msgId, MessageStatus.WRONG_REPORT.status))
			return Status.OTHER_ERROR ;
		
		return Status.OK;
	}

	/**
	 * 更新子账号的有效期，增加点数
	 * 
	 * */
	public Status p2s_updateAccount(UserBean user,String account, int point, long validDate) 
	{
		AccountBean accountBean = Globals.getAccountBuffer().get(account) ;
		if (accountBean == null)
			return Status.INVALID_VALUE ;
		if (user.getUserId() != accountBean.getUserId())
			return Status.USER_ID_MISMATCH;
		accountBean.setValidTime(validDate) ;
		accountBean.increasePoint(point) ;
		if (point != 0)
			Globals.logger(System.currentTimeMillis(),
					"mergeAccount", account, "", String.valueOf(point), String.valueOf(user.getUserId()));
		return Status.OK;
	}
	
}
